package com.woodws.mybatis.jpa.builder;

import org.apache.ibatis.mapping.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by maoxiaodong on 2016/11/9.
 */
public class Count extends AbstractBuilder<Count> {

    public Count() {
        this.sqlCommandType = SqlCommandType.SELECT;
    }

    public String toSql() {
        StringBuilder buf = new StringBuilder("<script> select count(1) from ");
        buf.append(this.fromClause);
        if (getWhereClause().length() > 0) {
            buf.append(" where ");
            buf.append(getWhereClause());
        }
        buf.append("</script>");
        return buf.toString();
    }

    @Override
    public void finish() {
        MappedStatement.Builder builder = new MappedStatement.Builder(configuration, id, getSqlSource(), sqlCommandType);
        String resultMapId = builder.id() + "-Inline";
        List<ResultMap> resultMaps = new ArrayList<ResultMap>();
        ResultMap.Builder resultMapBuilder = new ResultMap.Builder(
                configuration,
                resultMapId,
                Integer.class,
                new ArrayList<ResultMapping>());
        resultMaps.add(resultMapBuilder.build());
        builder.resultMaps(resultMaps);
        configuration.addMappedStatement(builder.build());
    }

}
